package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Override
    public PageResponse<RoleVo> page(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //查询数据
        Page<RoleVo> pages = roleMapper.selectByPage(roleDto);
        //封装分页信息pageResponse
        return PageResponse.of(pages, RoleVo.class);
    }

    @Override
    public List<String> findResources(Long roleId) {
        List<String> resources = roleResourceMapper.findResources(roleId);
        return resources;
    }

    @Override
    public void add(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Transactional
    @Override
    public void update(RoleDto roleDto) {
        //修改本表数据
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //TODO 有分配用户的时候不能禁用
        //修改中间表数据
        //删除原本的关联数据
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        if (ObjectUtils.isEmpty(checkedResourceNos)) {
            roleMapper.update(role);
            return;
        }
        roleResourceMapper.deleteByRoleId(roleDto.getId());
        //重新把新的关联数据插入
        List<RoleResource> roleResources = Arrays.stream(checkedResourceNos).map(o -> {
            return RoleResource.builder().resourceNo(o).roleId(roleDto.getId()).dataState(SuperConstant.DATA_STATE_0).build();
        }).collect(Collectors.toList());
        roleResources.forEach(roleResource -> roleResourceMapper.insert(roleResource));
    }
    @Transactional
    @Override
    public void delete(Long roleIds) {
        //TODO 有分配用户的时候不能删除
        //删除角色表数据
        roleMapper.deleteById(roleIds);
        //删除关联表数据
        roleResourceMapper.deleteByRoleId(roleIds);
    }

    @Override
    public List<RoleVo> initRoles() {
        List<RoleVo> roleVos =roleMapper.initRoles();
        roleVos.forEach(roleVo -> {
            roleVo.setCheckedResourceNos(roleResourceMapper.findResources(roleVo.getId()).toArray(new String[0]));
        });
        return roleVos;
    }

}
